<template>
  <!-- 全局注册三级分类的组件 -->
  <Category :scene="scene"></Category>
  <!-- 显示数据卡片 -->
  <el-card style="margin: 10px 0">
    <!-- 展示数据 -->
    <div v-show="scene == 0">
      <el-button
        @click="addAttr"
        type="primary"
        size="default"
        icon="Plus"
        :disabled="!categoryStore.C3Id"
      >
        添加商品属性
      </el-button>
      <el-table style="margin: 10px 0" border :data="attrArr">
        <el-table-column
          type="index"
          label="序号"
          width="80px"
          align="center"
        />
        <el-table-column label="属性名称" width="120" prop="attrName" />
        <el-table-column label="属性值名称">
          <template #="{ row }">
            <el-tag style="margin: 5px" v-for="item in row.attrValueList">
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateAttr(row)"
            ></el-button>
            <el-popconfirm
              :title="`你确定删除属性‘${row.attrName}’吗？`"
              @confirm="deleteAttr(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 更改或添加数据面板 -->
    <div v-show="scene == 1">
      <el-form :inline="true" size="normal">
        <el-form-item label="属性名称">
          <el-input
            placeholder="请你输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        :disabled="!attrParams.attrName"
        @click="addAttrValue"
      >
        添加属性值
      </el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-table border style="margin: 10px 0" :data="attrParams.attrValueList">
        <el-table-column
          width="80"
          label="序号"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-input
              :ref="(vc: any) => (inputAttr[$index] = vc)"
              v-show="row.flag"
              v-model="row.valueName"
              size="normal"
              placeholder="请输入属性名称"
              @blur="toLook(row, $index)"
            ></el-input>
            <div v-show="!row.flag" @click="toEdit(row, $index)">
              {{ row.valueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作">
          <template #="{ $index }">
            <el-button
              icon="Delete"
              type="primary"
              size="default"
              @click="attrParams.attrValueList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        size="default"
        @click="saveAttrValue"
        :disabled="attrParams.attrValueList.length == 0"
      >
        保存
      </el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import useCategoryStore from '@/store/modules/category'
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/type'
import { reqAttr, reqAddOrUpadateAttr, reqDeleteAttr } from '@/api/product/attr'
import { ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'

const categoryStore = useCategoryStore()
const attrArr = ref<Attr[]>()
let scene = ref<number>(0) //切换数据展示和更改或添加属性的面板
let attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
})
const inputAttr = ref<any>([])
//显示添加属性面板
const addAttr = () => {
  //每一次点击的时候,先清空一下数据再收集数据
  Object.assign(attrParams, {
    attrName: '', //新增的属性的名字
    attrValueList: [
      //新增的属性值数组
    ],
    categoryId: categoryStore.C3Id, //三级分类的ID
    categoryLevel: 3, //代表的是三级分类
  })
  //切换为添加与修改属性的结构
  scene.value = 1
}
//显示更新属性面板
const updateAttr = (row: Attr) => {
  scene.value = 1
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

//切换数据展示面板
const cancel = () => {
  scene.value = 0
}

//获取属性信息
const getAttr = async () => {
  const { C1Id, C2Id, C3Id } = categoryStore
  attrArr.value = []
  if (C3Id) {
    let result: AttrResponseData = await reqAttr(C1Id, C2Id, C3Id)
    if (result.code == 200) {
      attrArr.value = result.data
      // console.log(attrArr.value)
    }
  }
}

//监听第三级分类，变化时获取新的数据
watch(
  () => categoryStore.C3Id,
  () => {
    getAttr()
  },
)

//添加属性
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,
  })
  nextTick(() => {
    inputAttr.value[inputAttr.value.length - 1].focus()
  })
}

//保存添加属性
const saveAttrValue = async () => {
  let result: any = await reqAddOrUpadateAttr(attrParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
  scene.value = 0
}

//属性添加的查看模式
const toLook = (row: AttrValue, index: number) => {
  //属性名不可为空
  if (row.valueName.trim().length == 0) {
    attrParams.attrValueList.splice(index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不可以为空！',
    })
    return
  }
  //属性值不能重复
  const repeat = attrParams.attrValueList.find((item) => {
    if (row != item) return row.valueName == item.valueName
  })
  // 属性值不能重复
  if (repeat) {
    attrParams.attrValueList.splice(index, 1)
    ElMessage({
      type: 'error',
      message: '属性值重复！',
    })
    return
  }
  row.flag = false
}
//属性添加的编辑模式
const toEdit = (row: AttrValue, index: number) => {
  row.flag = true
  nextTick(() => {
    inputAttr.value[index].focus()
  })
}

//删除属性
const deleteAttr = async (id: number) => {
  let result: AttrResponseData = await reqDeleteAttr(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除属性成功！',
    })
    // 重新获取数据
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除属性失败！',
    })
  }
}

onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped></style>
